package com.huawei.Galenus.controller;

import com.alibaba.fastjson.JSON;
import com.huawei.Galenus.domain.Message;
import com.huawei.Galenus.utils.MD5Util;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

@RestController
@RequestMapping("/api/upload")
@CrossOrigin
@Api("文件上传相关接口")
public class UploadController {

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
    private Logger logger = LoggerFactory.getLogger(UploadController.class);

    @PostMapping("/singleFile")
    public Message singleFileUpload(MultipartFile file) {
        if (Objects.isNull(file) || file.isEmpty()) {
            logger.error("文件为空");
            return new Message().error(1111, "文件为空，请重新上传");
        }
        try {
            byte[] bytes = file.getBytes();
            String musicFilePath = UPLOAD_FOLDER + file.getOriginalFilename();
            Path path = Paths.get(musicFilePath);
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(UPLOAD_FOLDER));
            }
            Files.write(path, bytes);
            String hash = MD5Util.getFileMD5(new File(musicFilePath));
            System.out.println("-------------hash is " + hash);
            logger.debug("文件写入成功");
            return new Message().ok(6666, "文件上传成功")
                    .addData("hash", hash).addData("authfilehash", musicFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            return new Message().error(1111, "后端异常");
        }
    }
}
